let baseUrl = require("types.js").baseUrl;
// loading配置，请求次数统计
function startLoading() {
  wx.showLoading({
    title: '加载中...',
    icon: 'none'
  })
}
function endLoading() {
  wx.hideLoading();
}
// 声明一个对象用于存储请求个数
var needLoadingRequestCount = 0;
function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading();
  }
  needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return;
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    endLoading();
  }
};
// get/post请求
function fun(url, method, data) {
  data = data || {};
  let header = {
    "Terminal": "WeddingProgram"
  }
  wx.showNavigationBarLoading();
  showFullScreenLoading();
  let promise = new Promise(function (resolve, reject) {
    wx.request({
      url: baseUrl + url,
      header: header,
      data: data,
      method: method,
      success: function (res) {
        if (res.data.code === "E00") {
          setTimeout(() => {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2500
            })
          },0)
          reject(res.data.msg);
        }
        if (res.data.code === "E10002"){
          setTimeout(() => {
            wx.showToast({
              title: '请登陆!',
              icon: "none",
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.navigateTo({
                    url: '../../login/login',
                  })
                }, 2000) //延迟时间
              }
            });
          }, 0);
          reject(res.data.msg);
        }
        resolve(res.data.data);
        tryHideFullScreenLoading();
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ error: '网络错误', code: 0 });
        tryHideFullScreenLoading();
      },
      complete: function () {
        wx.hideNavigationBarLoading();
      }
    });
  });
  return promise;
}

module.exports = {
  "get": function (url, data, header) {
    return fun(url, "GET", data, header);
  },
  "post": function (url, data, header) {
    return fun(url, "POST", data, header);
  }
};